package com.link.base.base.youtu.service;

import javax.annotation.Resource;

import com.link.base.base.youtu.dao.mybatis.mapper.AppMapper;
import com.link.base.base.youtu.model.App;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;


/**
 * @author 郭闪
 * @date 2018-11-05
 */
@Service
public class AppServiceImpl extends BasicServiceImpl<App> implements AppService {

    /**
     * 有效的app信息在redis中的key的部分信息，TENCENT_YOUTU_APP_INFO_ + corpId
     */
    private static final String YOUTU_REDISKEY = "TENCENT_YOUTU_APP_INFO_";

    @Resource
    private AppMapper appMapper;

    @Override
    public BasicMapper<App> getBasicMapper() {
        return appMapper;
    }

    @Override
    public void effectApp(App app) {
        LinkRedisClient jedis = null;
        try {
            App newApp = appMapper.queryById(app);
            String redisKey = YOUTU_REDISKEY + newApp.getCorpid();
            jedis = RedisUtil.getJedis();
            // 删除旧的有效项目数据
            jedis.del(redisKey);
            // 写入核心项目数据，其余数据会在接待时自动基于新项目下的已有数据信息重新构建
            jedis.hset(redisKey, "YOUTU_APPID", newApp.getAppId());
            jedis.hset(redisKey, "YOUTU_APP_LNK_ID", String.valueOf(newApp.getId()));
            jedis.hset(redisKey, "YOUTU_APP_GROUP_NUM", "0");
            jedis.hset(redisKey, "YOUTU_APP_BUCKET_NAME", newApp.getBucket());
            jedis.hset(redisKey, "YOUTU_APP_SECRET_ID", newApp.getSecretId());
            jedis.hset(redisKey, "YOUTU_APP_SECRET_KEY", newApp.getSecretKey());
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        } finally {
            if (jedis != null) {
                RedisUtil.returnResource(jedis);
            }
        }
    }
}

